import type { Nullable } from '@/types/global'
import type { DescriptionActionType, DescriptionProps, UseDescriptionType } from './type'
import { getDynamicProps } from '@/components/BasicForm/src/common/gloab'
import { nextTick, onUnmounted, ref, unref, watch } from 'vue'
type Props = Partial<DescriptionProps>

export function useDescription(props?: Props): UseDescriptionType {
  const descrRef = ref<Nullable<DescriptionActionType>>(null)
  const loadedRef = ref<Nullable<boolean>>(false)

  async function getDescription() {
    const desc = unref(descrRef)
    if (!desc) {
      console.error('获取descrRef失败！')
    }
    await nextTick()
    return desc as DescriptionActionType
  }

  function register(instance: DescriptionActionType) {
    onUnmounted(() => {
      descrRef.value = null
      loadedRef.value = null
    })

    if (unref(loadedRef) && instance === unref(descrRef)) return
    descrRef.value = instance
    loadedRef.value = true
    watch(
      () => props,
      () => {
        props && instance.setProps(getDynamicProps(props))
      },
      {
        immediate: true,
        deep: true,
      },
    )
  }
  const methods: DescriptionActionType = {
    setProps: async (formProps: Partial<Props>) => {
      const descr = await getDescription()
      descr.setProps(formProps)
    },
  }
  return [register, methods]
}
